/*
 * @Date: 2023-03-21 16:35:56
 * @LastEditors: Zireael 1193875164@qq.com
 * @LastEditTime: 2023-03-21 22:01:37
 * @FilePath: \A19\backend\src\flowNodes\encry.ts
 */
import { BaseServer, WsServer, HttpServer, HttpConnection } from 'tsrpc';
import { ServiceType } from "../shared/protocols/serviceProto";
import { EncryptUtil } from "../shared/EncryptUtil";
import { TextEncoder } from 'util';

// const secret = "妄想☆ふぇてぃっしゅ!";
// const encoder = new TextEncoder()
// console.log(encoder.encode(secret));

export default async function (server: HttpServer<ServiceType>,wsServer:WsServer<ServiceType>) {
  // 发送前加密
  server.flows.preSendDataFlow.push((v) => {
    if (v.data instanceof Uint8Array) {
      v.data = EncryptUtil.encrypt(v.data);
    }
    return v;
  });
  // 接收前解密
  server.flows.preRecvDataFlow.push((v) => {
    // let conn = v.conn as HttpConnection;
    // if(conn.httpReq.method === 'GET'){
    //   return v;
    // }
    
    if (v.data instanceof Uint8Array) {
      v.data = EncryptUtil.decrypt(v.data);
    }
    return v;
  });

  wsServer.flows.preSendDataFlow.push(v =>{
    // let conn = v.conn as HttpConnection;
    // console.log(conn);
    // if(conn.httpReq.method === 'GET'){
    //   return v;
    // }

    if (v.data instanceof Uint8Array) {
      v.data = EncryptUtil.encrypt(v.data);
    }
    return v
  })

  wsServer.flows.preRecvDataFlow.push(v =>{
    if (v.data instanceof Uint8Array) {
      v.data = EncryptUtil.decrypt(v.data);
    }
    return v
  })
}
